<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <todo-header></todo-header>
        <!--第一个todolist组件-->
        <todo-list :list="list">
          <template #list> <i style="color: red">(>^ω^<)喵</i> </template>
          <template #item="{text}"> <strong style="color: red">{{text}}</strong> </template>
        </todo-list>
        <!--第二个todolist组件-->
       <!-- <todo-list :list="list">
          <template #list> <i style="color:green;">(>`ω`<)汪</i> </template>
          <template #item="{text}"> <i style="color:green;">{{text}}</i> </template>
        </todo-list>-->
        <todo-footer :list="list"></todo-footer>
      </div>
    </div>
  </div>
</template>

<script>
  import header from "./components/todo-header";
  import list from "./components/todo-list";
  import footer from "./components/todo-footer";
  export default {
    name: 'App',
    data(){
      return {
        list:[]
      }
    },
    components:{
      "todo-header":header,
      "todo-list":list,
      "todo-footer":footer,
    },
    methods:{
      //新增待办任务的函数
      addTask(newTask){
        this.list.push(newTask)
      },
      //删除指定待办任务的函数
      delTask(id){
        this.list = this.list.filter((item)=>item.id !== id)
      },
      //选中或消除对应的待办任务
      checked(id,val){
        // item.checked = val;
        var item = this.list.find(element => element.id === id);
        item.checked = val;
      },
      //清除已完成任务
      clear(){
        this.list = this.list.filter(item => !item.checked)
      },
      //全选全不选
      checkAll(val){
        //val : 全选按钮的最新状态
        this.list.forEach((item)=>{
          item.checked = val
        })
      }
    },
    mounted(){
      //从localstorage中读取list相关的数据
      this.list = JSON.parse(localStorage.getItem("todo-list")) || [];


      this.$bus.$on("addTask",this.addTask) //header组件触发
      this.$bus.$on("delTask",this.delTask) //item组件触发
      this.$bus.$on("checked",this.checked)//item组件触发
      this.$bus.$on("clear",this.clear)//footer组件触发
      this.$bus.$on("checkAll",this.checkAll)//footer组件触发
    },
    watch:{
      list:{
        deep:true,
        handler(){
          //让localStorage记录下list的变化
          localStorage.setItem("todo-list",JSON.stringify(this.list))
        }
      }
    }
  }
</script>

<style scoped>
  /*app*/
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>
